from models_goods.oo import *
from datetime import datetime
from django.db.models import Q
from django.utils.timezone import now, timedelta


# 资产转移的流水查询（按保管人查询）
def water_search_protector(request):
    # 获取所有的保管人
    user_name_list = AllUserName().get_info()

    context = {"user_name_list": user_name_list, }
    if request.method == 'GET':
        return render(request, 'water_search/water_search_protector.html', context)

    elif request.method == 'POST':
        # 获取water_search.html中的数据库内的查询的名字
        all_water_list = RunningWater.objects.filter(user=request.POST['asset']).values_list(
            'goods__name', 'detail', 'user__name', 'ctrl_user__name', 'pub_date')

        # 获取search.html中的asset数据，即资产转移保管人的id（注:此为字符串类型）
        asset = request.POST.get('asset')
        asset = int(asset)

        # 下拉菜单失效
        # context = {"all_water_list": all_water_list, }
        # 下拉菜单完好

        context = {"user_name_list": user_name_list,  'asset': asset}
        context.update({"all_water_list": all_water_list, })
        return render(request, 'water_search/water_search_protector.html', context)
# -----------------------------------------------


# 按单个时间进行查询
def water_search_date(request):
    # 2、获取数据库时间
    all_time_list = RunningWater.objects.all()
    if request.method == 'GET':
        context = {'all_time_list': all_time_list}
        return render(request, 'water_search/water_search_date.html', context)

    elif request.method == 'POST':
        # 1、获取water_search_date.html中asset的数据,即录入时间的id
        water_id01 = request.POST.get('asset')
        # 2、将字符串id转换成整数id
        water_id = int(water_id01)
        # 3、通过id直接在数据库中获取录入时间
        pub_date01 = RunningWater.objects.get(pk=water_id).pub_date
        # 将获取的时间转换为可以使用时间

        one_water_list = RunningWater.objects.filter(pk=water_id01).values_list(
            'goods__name', 'detail', 'user__name', 'ctrl_user__name', 'pub_date')
        context = {
            "one_water_list": one_water_list,
            "water_id": water_id,
            'all_time_list': all_time_list,
             }
        return render(request, 'water_search/water_search_date.html', context)


# 尝试二：
"""
# 获取water_search_date.html中asset的数据,即录入时间的id
water_id = request.POST.get('asset')
# 直接获取时间，并将获取的时间转换为可以使用时间
pub_date01 = '%Y-%m-%d %H:%M:%S'.format(RunningWater.objects.filter(
        pub_date=request.POST['asset']).values_list('pub_date'))
        
print(water_id)
print(pub_date01)
"""
# 尝试一：
"""
# 获取water_search_date.html中asset的数据,即录入时间的id
water_id01 = request.POST.get('asset')
pub_date01 = request.POST.get('asset').pub_date
# 现在有一个问题，如何将pub_date01转换为可以使用的时间
# 将获取的时间转换为可以使用时间
water_id = int(water_id01)
print(water_id01)
print(water_id)
print(pub_date01)
"""

# -----------------------------------------------

"""
*规则如下:*
> *time距离现在的时间间隔*
> 1. *如果时间间隔小于1分钟以内，那么就显示“刚刚”*
> 2. *如果是大于1分钟小于1小时，那么就显示“xx分钟前”*
> 3. *如果是大于1小时小于24小时，那么就显示“xx小时前”*
> 4. *如果是大于24小时小于30天以内，那么就显示“xx天前”*
> 5. *否则就是显示具体的时间 2017/10/20 16:15*
"""

# 按时间段进行查询  尝试一
"""
def water_search_date(request):
    # 现获取现在的时间，再获取数据库的时间，相减之后，时间差大于xxx不显示，小于的部分显示

    # 1、获取现在时间
    now_time = datetime.now()
    print(now_time)   # 2018-11-22 11:04:04.664814
    # 2、获取数据库时间
    time_list = RunningWater.objects.get(pk=5).pub_date
    print(time_list)  # 2018-11-21 10:18:52.850710
    # 获取时间差
    delta = now_time-time_list
    print(delta)
    # 将时间差统一设置为秒 24h=24*60*60s
    all_seconds = delta.total_seconds()
    print(all_seconds)
    ''' 
    1. *如果时间差小于24小时，那么就显示*
    2. *如果时间差大于24小时，那么就不显示*
    '''
    if all_seconds < 24*60*60:
        all_water_list = RunningWater.objects.all().values_list(
            'goods__name', 'detail', 'user__name', 'ctrl_user__name', 'pub_date')
        context = {"all_water_list": all_water_list, }
        return render(request, 'water_search/water_search_date.html', context)
    else:
        context = {
            "mes": "超出一天，无法显示"
        }
        return render(request, 'water_search/water_search_date.html', context)

    # return HttpResponse('<script>alert("OK")</script>')
"""

"""
def water_search_period(request):
    # 时间小于2018-11-22 22:0:0的流水显示
    res0 = RunningWater.objects.filter(Q(pub_date__lt=datetime(2018, 11, 22, 22, 0, 0)))
    # 时间小于2018-11-22 8:8:8的流水显示
    res1 = RunningWater.objects.filter(Q(pub_date__lt=datetime(2018, 11, 22, 8, 8, 8)))
    # 时间大于2018-11-22 12:0:0的流水显示
    res2 = RunningWater.objects.filter(Q(pub_date__gt=datetime(2018, 11, 22, 12, 0, 0)))
    # 时间大于2018-11-22 12:0:0 或者 小于2018-11-21 10:30:0的流水显示
    res3 = RunningWater.objects.filter(
        Q(pub_date__gt=datetime(2018, 11, 22, 12, 0, 0)) | Q(pub_date__lt=datetime(2018, 11, 21, 10, 30, 0)))
    # 时间大于2018-11-21 10:30:0 并且 小于2018-11-22 10:30:0的流水显示
    res4 = RunningWater.objects.filter(
        Q(pub_date__gt=datetime(2018, 11, 21, 10, 30, 0)) & Q(pub_date__lt=datetime(2018, 11, 22, 10, 30, 0)))

    print('0', '-' * 15)
    for s in res0: print('{},{},{},{},{}'.format(s.goods, s.detail, s.user, s.ctrl_user, s.pub_date))
    print('1', '-' * 15)
    for s in res1: print('{},{},{},{},{}'.format(s.goods, s.detail, s.user, s.ctrl_user, s.pub_date))
    print('2', '-' * 15)
    for s in res2: print('{},{},{},{},{}'.format(s.goods, s.detail, s.user, s.ctrl_user, s.pub_date))
    print('3', '-' * 15)
    for s in res3: print('{},{},{},{},{}'.format(s.goods, s.detail, s.user, s.ctrl_user, s.pub_date))
    print('4', '-' * 15)
    for s in res4: print('{},{},{},{},{}'.format(s.goods, s.detail, s.user, s.ctrl_user, s.pub_date))

    return HttpResponse('OK')
"""
# -----------------------------------------------


# 按时间段进行展示流水  尝试二
# 使用Q表达式，查询操作，过滤器,lt是小于,gt是大于,&并且，|或者
def water_search_period(request):
    # 尝试一
    """
    date1 = now().date() + timedelta(days=-1)  # 昨天
    date2 = now().date() + timedelta(days=0)  # 今天
    date3 = now().date() + timedelta(days=1)  # 明天
    print(date1, date2, date3)
    """

    # 直接将时间差用"精确查询"算出
    # 1、一周内，小于现在的时间和大于减去7天的时间
    date1 = now().date() + timedelta(days=-7)
    res1 = RunningWater.objects.filter(Q(pub_date__lt=datetime.now()) & Q(pub_date__gt=date1))

    # 2、一月内，小于现在的时间和大于减去30天的时间
    date2 = now().date() + timedelta(days=-30)
    res2 = RunningWater.objects.filter(Q(pub_date__lt=datetime.now()) & Q(pub_date__gt=date2))

    # 3、后半年内，小于现在的时间和大于6月份的时间----报错（TypeError at /water/period/，expected string or bytes-like object）
    # 错误原因： pub_date__gt=(2018, 6, 30, 23, 50, 59)格式错误，datetime(2018, 6, 30, 23, 50, 59)
    # res3 = RunningWater.objects.filter(Q(pub_date__lt=datetime.now()) & Q(pub_date__gt=(2018, 6, 30, 23, 50, 59)))
    # for i in res3:
    #     print(i.goods, i.detail, i.pub_date)

    # 3、半年内，小于现在的时间和大于前6个月的时间
    date3 = now().date() + timedelta(days=-180)
    res3 = RunningWater.objects.filter(Q(pub_date__lt=datetime.now()) & Q(pub_date__gt=date3))

    # 4、后半年内，1--6月的时间
    res4 = RunningWater.objects.filter(Q(pub_date__lt=datetime(2018, 6, 30, 1, 0, 0)) & Q(pub_date__gt=datetime(2018, 1, 1, 1, 0, 0)))

    # 5、3天内的数据
    date5 = now().date() + timedelta(days=-3)
    res5 = RunningWater.objects.filter(Q(pub_date__lt=datetime.now()) & Q(pub_date__gt=date5))

    context = {"res1": res1, "res2": res2, "res3": res3, "res4": res4, "res5": res5, }
    return render(request, 'water_search/water_search_period.html', context)

    # return HttpResponse('<script>alert("ok")</script>')






